﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Ruleweaver.Rules.CheckMethods
{
	public sealed class IsInMethod : CheckMethod
	{
		public IsInMethod(IEnumerable<object> values)
		{
			Contract.Requires(values != null);

			Values = values.ToList().AsReadOnly();
		}

		public IsInMethod(params object[] values) : this(values as IEnumerable<object>)
		{}

		public ReadOnlyCollection<object> Values { get; private set; }

		protected override bool SupportsTargetType(Type targetType)
		{
			return true;
		}

		protected override MethodInfo GetMethod(Type targetType, Type checkType)
		{
			var valuesType = typeof(IEnumerable<>).MakeGenericType(targetType);

			return typeof(Checkable)
				.GetMethods(BindingFlags.Public | BindingFlags.Static)
				.Where(method => method.Name == "IsIn")
				.Where(method => method.GetParameters().Skip(1).First().ParameterType == valuesType)
				.First()
				.MakeGenericMethod(targetType);
		}
	}
}